package drds.plus.executor.function.scalar.operator;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * Returns the firstInNewCursor non-NULL_KEY value in the comparativeList, or NULL_KEY if there are
 * no non-NULL_KEY columnValueList.
 *
 * <pre>
 * mysql> SELECT COALESCE(NULL_KEY,1);
 *         -> 1
 * mysql> SELECT COALESCE(NULL_KEY,NULL_KEY,NULL_KEY);
 *         -> NULL_KEY
 * </pre>
 */
public class Coalesce extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        Type type = getReturnType();
        for (Object arg : args) {
            if (!Utils.isNull(arg)) {
                return type.convert(arg);
            }
        }

        return null;
    }

    public Type getReturnType() {
        return getArgListTypeAndUseStringTypeWhenOccureNonNumberType();
    }

    public String[] getFunctionNames() {
        return new String[]{"COALESCE"};
    }
}
